package mega.awesome.assignment3;

import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;

public class GpsActivity extends Activity {

	private LocationManager locationManager;
	private TextView lat, lon, alt, bear, accuracy;
	private String provider;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gps);
		
		lat = (TextView)findViewById(R.id.latitudevalue);
		lon = (TextView)findViewById(R.id.longitudevalue);
		alt = (TextView)findViewById(R.id.altitudevalue);
		bear = (TextView)findViewById(R.id.bearingvalue);
		accuracy = (TextView)findViewById(R.id.gpsvalue);
		
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(true);
		criteria.setBearingRequired(true);
		criteria.setCostAllowed(true);
		
		provider = locationManager.getBestProvider(criteria, true);
		Location location = locationManager.getLastKnownLocation(provider);
		
		
		updateViewsWithLocation(location);
	}
	
	private void updateViewsWithLocation(Location location) {
		lat.setText("" + location.getLatitude());
		lon.setText("" + location.getLongitude());
		alt.setText("" + location.getAltitude());
		bear.setText("" + location.getBearing());
		accuracy.setText("" + location.getAccuracy());
	}
	
	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateViewsWithLocation(location);
		}
		
		public void onProviderDisabled(String provider){}
		public void onProviderEnabled(String provider) {}
		public void onStatusChanged(String provider, int status, Bundle extras) {}
	};

	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider,
                0, // 0.5min
                1,   // 1m
                locationListener);
	}
	
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(locationListener);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_gps, menu);
		return true;
	}

}
